//
//  LXStatusDAL.swift
//  weibo
//
//  Created by lixin on 16/4/28.
//  Copyright © 2016年 lixin. All rights reserved.
//

import UIKit

class LXStatusDAL: NSObject {

    //MARK: - 获取微博首页数据方法
    class func getHomeStatus(since_id: Int64, max_id: Int64, callback:(array: [[String: AnyObject]])->()){
        
        // 判断本地是否有数据
        let result = checkoutCacheStatus(since_id, max_id: max_id)

        if result.count == 0{
            LXNetworkTools.sharedTools.loadStatus(LXUserAccountTools.sharedTools.accessToken!, since_id: since_id, max_id: max_id, callback: { (response, error) -> () in
                
                if error != nil{
                    
                    callback(array: [])
                    
                    print(error)
                    
                    return
                }
                // 判断数据是否存在、是否是一个数组
                guard let array = response?["statuses"] as? [[String: AnyObject]] else{
                    
                    print("返回的数据不是一个数组")
                    
                    callback(array: [])
                    
                    return
                }
               
                callback(array: array)
                
                LXStatusDAL.saveStatus(array)
            })
            
        }else{
          
            callback(array: result)
        }
    }
    
    // 查询本地数据
    class func checkoutCacheStatus(since_id: Int64, max_id: Int64) -> [[String: AnyObject]] {
       
        if since_id == 0 && max_id == 0{
            
            return []
        }
        
        // 获取userId
        let userId = LXUserAccountTools.sharedTools.userAccount!.uid!
        
        var sql = "SELECT status FROM T_Status WHERE userId = \(userId) "
        
        // 下拉刷新
        if since_id > 0{
            
            sql += " AND statusId > \(since_id)"
        }
        
        // 上拉加载更多
        if max_id > 0{
            
            sql += " AND statusId < \(max_id)"
        }
        
        // 限制查询数据的条数
        sql += " ORDER BY statusId DESC LIMIT 20"
        
        var tempArray: [[String: AnyObject]] = [[String: AnyObject]]()
        
        
        SQLManager.sharedTools.queue.inDatabase { (db) -> Void in
            
            do{
                let res = try db.executeQuery(sql)
                
                while res.next(){
                    
                    let status = res.dataForColumn("status")
                    
                    let dic = try! NSJSONSerialization.JSONObjectWithData(status, options: []) as! [String: AnyObject]
                    
                    tempArray.append(dic)
                }
                
            }catch{
                
                print(error)
            }
        }
        
        return tempArray
    }
    
    // 保存从网络加载回来的数据
    class func saveStatus(array: [[String: AnyObject]]) {
       
        let userId = LXUserAccountTools.sharedTools.userAccount!.uid!
       
        let sql = "INSERT OR REPLACE INTO T_Status (statusId,status,userId) VALUES (?,?,?)"
        
        SQLManager.sharedTools.queue.inTransaction { (db, rollback) -> Void in
            
            for dic in array{
                
                do{
                    let statusId = dic["id"] as! NSNumber
                    
                    let status = try! NSJSONSerialization.dataWithJSONObject(dic, options: [])
                    
                    try db.executeUpdate(sql, statusId,status,userId)
                    
                }catch{
                    
                    print(error)
                    
                    rollback.memory = true
                }
            }
        }
    }
}
